<template>
  <div class="dictionary-view">
    <el-row :gutter="20">
      <el-col :span="11">
        <div class="box">
          <div class="py-3 flex justify-between items-center">
            <div class="flex">
              <el-input
                v-model="queryParams.search"
                placeholder="请输入名称"
                size="small"
                clearable
              />
              <el-button
                class="ml-2"
                type="primary"
                size="small"
                @click="reset"
              >
                重置
              </el-button>
            </div>
            <el-button
              type="primary"
              size="small"
              icon="Plus"
              @click="dictionaryDialog.show('0')"
            >
              新增
            </el-button>
          </div>
          <Table :data="parentTableDataComputed" :selectColumn="false">
            <TableColumn
              label="名称"
              prop="dictionaryValue"
              :min-width="
                getColumnWidth(parentTableDataComputed, 'dictionaryValue', 80)
              "
            />
            <TableColumn
              label="描述"
              prop="dictionaryCode"
              :min-width="
                getColumnWidth(parentTableDataComputed, 'dictionaryCode', 80)
              "
            />
            <TableColumn label="操作" width="220px" fixed="right">
              <template #default="{ row }">
                <el-button
                  type="success"
                  size="small"
                  @click="handleCurrentChange(row)"
                >
                  详情
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  :disabled="row.dictionaryValue === dataPermissionBusinessName"
                  @click="dictionaryDialog.show('0', row)"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  :disabled="row.dictionaryValue === dataPermissionBusinessName"
                  @click="handleDelete(row)"
                >
                  删除
                </el-button>
              </template>
            </TableColumn>
          </Table>
        </div>
      </el-col>
      <el-col :span="13">
        <div class="box">
          <div class="flex justify-between items-center py-2 border-b">
            <div>
              字典详情
              {{
                parentRow.dictionaryValue !== '0'
                  ? ` - ${parentRow.dictionaryCode}`
                  : ''
              }}
            </div>
            <el-button
              type="primary"
              size="small"
              icon="Plus"
              :disabled="parentRow.dictionaryValue === '0'"
              @click="dictionaryDialog.show(parentRow.dictionaryValue)"
            >
              新增
            </el-button>
          </div>
          <Table
            class="mt-4"
            :data="dictionaryTableData"
            :empty-text="
              parentRow.dictionaryValue === '0' ? '请先选择字典' : '暂无数据'
            "
            :select-column="false"
          >
            <TableColumn
              label="字典标签"
              prop="dictionaryCode"
              :min-width="
                getColumnWidth(dictionaryTableData, 'dictionaryCode', 80)
              "
            />
            <TableColumn
              label="字典值"
              prop="dictionaryValue"
              :min-width="
                getColumnWidth(dictionaryTableData, 'dictionaryValue', 80)
              "
            />
            <TableColumn label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button
                  type="primary"
                  size="small"
                  @click="dictionaryDialog.show(parentRow.dictionaryValue, row)"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete(row)"
                >
                  删除
                </el-button>
              </template>
            </TableColumn>
          </Table>
        </div>
      </el-col>
    </el-row>
    <DictionaryDialog ref="dictionaryDialog" @update="handleUpdate" />
  </div>
</template>

<script setup lang="ts">
import { deleteDictionaryEntries, getDictionary } from '@/api/sys/dictionary'
import DictionaryDialog from '@/views/sys/dictionary/DictionaryDialog.vue'
import { ElMessageBox } from 'element-plus'
import { computed, onMounted, reactive, ref, useTemplateRef } from 'vue'
import TableColumn from '@/components/table/TableColumn.vue'
import Table from '@/components/table/Table.vue'
import { getColumnWidth } from '@/plugins/util'
import useDictionaryStore from '@/stores/dictionary'
import { Message } from '@/hooks/message'

const dataPermissionBusinessName = 'dataPermissionBusinessName'

const dictionaryStore = useDictionaryStore()

const dictionaryDialog =
  useTemplateRef<InstanceType<typeof DictionaryDialog>>('dictionaryDialog')

const queryParams = reactive({
  search: '',
})
const parentRow = reactive({
  dictionaryCode: '',
  dictionaryValue: '0',
})
const parentTableData = reactive([])
const dictionaryTableData = ref([])

const parentTableDataComputed = computed(() => {
  return parentTableData.filter((item) => {
    if (queryParams.search) {
      return (
        item.dictionaryCode.includes(queryParams.search) ||
        item.dictionaryValue.includes(queryParams.search)
      )
    } else {
      return true
    }
  })
})

async function reset() {
  Object.assign(queryParams, {
    search: '',
  })
}

async function init() {
  const { data } = await getDictionary()
  if (data.status === 200) {
    parentTableData.length = 0
    parentTableData.push(...data.data)
  }
}

function handleUpdate(parent: string) {
  dictionaryStore.reset()
  dictionaryTableData.value = []
  if (parent === '0') {
    init()
  } else {
    handleParentRowClick(parent)
  }
}

async function handleCurrentChange(row: any) {
  parentRow.dictionaryValue = row.dictionaryValue
  parentRow.dictionaryCode = row.dictionaryCode
  await handleParentRowClick(parentRow.dictionaryValue)
}

async function handleParentRowClick(parent: string) {
  const { data } = await getDictionary(parent)
  if (data.status === 200) {
    dictionaryTableData.value = data.data
  }
}

async function handleDelete(row: any) {
  ElMessageBox.confirm(
    `确定删除 ${row.dictionaryCode} - ${row.dictionaryValue} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    },
  )
    .then(async () => {
      const { data } = await deleteDictionaryEntries(row.id)
      if (data.status === 200) {
        Message({
          message: data.message,
          type: 'success',
        })
        handleUpdate(row.parent)
      }
    })
    .catch(() => {})
}

onMounted(() => {
  init()
})
</script>

<style scoped lang="scss">
.box {
  @apply py-2 px-4;
  @apply bg-white rounded-md shadow-md;
  @apply border;
  height: calc(100vh - 150px);
}
</style>
